package com.xiaoshuidi.cloud.module.report.xxljob;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.module.report.constant.ContractCompanyTypeEnum;
import com.xiaoshuidi.cloud.module.report.constant.RenterTypeEnum;
import com.xiaoshuidi.cloud.module.report.dal.DO.ContractRoomDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.ContractSettlementDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.ContractSettlementDetailDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.RoomHouseDO;
import com.xiaoshuidi.cloud.module.report.dal.DO.report.DepositDetailDO;
import com.xiaoshuidi.cloud.module.report.dal.mapper.ContractRoomMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.ContractSettlementDetailMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.ContractSettlementMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.RoomHouseMapper;
import com.xiaoshuidi.cloud.module.report.dal.mapper.report.DepositDetailMapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 退款押金扣除job
 */
@Component
@Slf4j
public class DepositRefundHandleJob {

    @Resource
    private DepositDetailMapper depositDetailMapper;
    @Resource
    private ContractSettlementMapper contractSettlementMapper;
    @Resource
    private ContractSettlementDetailMapper contractSettlementDetailMapper;
    @Resource
    private ContractRoomMapper contractRoomMapper;
    @Resource
    private RoomHouseMapper roomHouseMapper;

    @XxlJob("depositRefundHandleJob")
    @TenantIgnore
    public void execute() {
        //获取押金报表流出押金的最大订单id
        Long maxOutId = depositDetailMapper.selectOutMaxId();
        if(ObjectUtils.isEmpty(maxOutId)) {
            //之前没有退租的押金数据
            List<ContractSettlementDO> contractSettlementDOS = contractSettlementMapper.selectList();
            handlerDepositRefund(contractSettlementDOS);
        } else {
            List<ContractSettlementDO> contractSettlementDOS = contractSettlementMapper.selectListById(maxOutId);
            handlerDepositRefund(contractSettlementDOS);
        }
    }

    private void handlerDepositRefund(List<ContractSettlementDO> contractSettlementDOS){
        if(CollectionUtils.isEmpty(contractSettlementDOS)){
            return;
        }
        contractSettlementDOS = contractSettlementDOS.stream().filter(e->"clear".equals(e.getClearedStatus())).collect(Collectors.toList());
        if(CollectionUtils.isEmpty(contractSettlementDOS)){
            return;
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        List<DepositDetailDO> list = new ArrayList<>();
        for (ContractSettlementDO settlementDO : contractSettlementDOS) {
            DepositDetailDO depositDetailDO = new DepositDetailDO();
            depositDetailDO.setApartmentId(settlementDO.getApartmentId())
                    .setSettlementId(settlementDO.getId())
                    .setRoomId(settlementDO.getRoomId())
                    .setContractId(settlementDO.getContractId())
                    .setContractNo(settlementDO.getContractNo())
                    .setRenter(settlementDO.getCustomerName())
                    .setTrader(settlementDO.getCustomerName())
                    .setDirection("流出")
                    .setPayMethod("银行转账")
                    .setPayDate(settlementDO.getEvictionTime())
                    .setTenantId(settlementDO.getTenantId())
                    .setDeptId(settlementDO.getDeptId());
            //获取退租押金金额
            List<ContractSettlementDetailDO> settlementDetailDOS = contractSettlementDetailMapper.selectByOrderIds(Arrays.asList(settlementDO.getId()));
            if(CollectionUtils.isNotEmpty(settlementDetailDOS)){
                BigDecimal refundAmount = settlementDetailDOS.stream().filter(e -> e.getFeeId()==2).map(ContractSettlementDetailDO::getRefundableAmount)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                if(BigDecimal.ZERO.compareTo(refundAmount)==0){
                    continue;
                }
                depositDetailDO.setAmount(refundAmount);
            }else {
                //没有明细 直接下一笔
                continue;
            }
            //获取合同信息
            ContractRoomDO contractDO = contractRoomMapper.selectById(settlementDO.getContractId());
            depositDetailDO.setRenterType(RenterTypeEnum.getValueByType(contractDO.getCustomerType()));
            depositDetailDO.setContractType(ContractCompanyTypeEnum.getValueByType(contractDO.getCustomerType()));
            String contractPeriod = contractDO.getStartTime().format(formatter) + "~" + contractDO.getEndTime().format(formatter);
            depositDetailDO.setContractPeriod(contractPeriod);
            depositDetailDO.setHandleFlag(1);
            //集中式和分散式拼凑方法不一样
            //查询房源信息
            RoomHouseDO houseDO = roomHouseMapper.selectById(settlementDO.getRoomId());
            if(houseDO ==null){
                log.error("====脏数据 有房间id无房源数据 roomId:{}",settlementDO.getRoomId());
                continue;
            }
            StringBuilder houseName = new StringBuilder(houseDO.getArea()).append(houseDO.getBuildingNo()).append("栋");
            if (houseDO.getIsConcentrated()) {
                //集中式 小区名-楼栋-房源名称   room_house.area - room_house.building_no栋 - room_house.name
                depositDetailDO.setHouseResource(houseName.append(houseDO.getName()).toString());
            } else {
                //分散式  小区名-楼栋-单元-房源名称 room_house.area - room_house.building_no栋 - room_house.unit_no单元 - room_house.name
                depositDetailDO.setHouseResource(houseName.append(houseDO.getUnitNo()).append("单元").append(houseDO.getName()).toString());
            }
            list.add(depositDetailDO);
        }
        if(CollectionUtils.isNotEmpty(list)){
            depositDetailMapper.insertBatch(list,list.size());
        }
    }

}